<template>
	<view>
		<view class="shop_data shop_data_top">
			<view class="shop_data_title">店铺记录</view>
			<view class="deal" v-if="!loadding">
				<view class="title">今日成交量</view>

				<!-- 时间范围选择器 -->
				<view class="time-range-picker">
					<view class="time-item" @click="openPicker('start')">
						<text>开始时间</text>
						<view class="time-value">
							<text>{{ startDateStr || '请选择' }}</text>
							<u-icon name="arrow-right" color="#999"></u-icon>
						</view>
					</view>
					<view class="time-item" @click="openPicker('end')">
						<text>结束时间</text>
						<view class="time-value">
							<text>{{ endDateStr || '请选择' }}</text>
							<u-icon name="arrow-right" color="#999"></u-icon>
						</view>
					</view>
				</view>

				<view class="d-s-c  deal_list">
					<view class="deal_item d-c  d-c-c">
						<view class="item_num">{{order.totalRent}}</view>
						<view>总租金</view>
					</view>
					<view class="deal_item d-c  d-c-c">
						<view class="item_num">{{order.rentRepaid}}</view>
						<view>待还租金</view>
					</view>
					<view class="deal_item d-c d-c-c">
						<view class="item_num">{{order.overdueRate}}</view>
						<view>逾期率</view>
					</view>
					<view class="deal_item d-c  d-c-c">
						<view class="item_num">{{order.rentPaid}}</view>
						<view>已还租金</view>
					</view>
					<view class="deal_item d-c  d-c-c">
						<view class="item_num">{{order.advanceRent}}</view>
						<view>实付金额</view>
					</view>
					<view class="deal_item d-c  d-c-c">
						<view class="item_num">{{order.activeRepayment}}</view>
						<view>主动还款</view>
					</view>
					<view class="deal_item d-c  d-c-c">
						<view class="item_num">{{order.pendingBuyout}}</view>
						<view>买断金额</view>
					</view>
					<view class="deal_item d-c  d-c-c">
						<view class="item_num">{{order.yuqiRepayment}}</view>
						<view>逾期金额</view>
					</view>
					<view class="deal_item d-c  d-c-c">
						<view class="item_num">{{order.daikouRepayment}}</view>
						<view>代扣金额</view>
					</view>
					<view class="deal_item d-c  d-c-c">
						<view class="item_num">{{order.hetong}}</view>
						<view>合同金额</view>
					</view>
					<view class="deal_item d-c  d-c-c">
						<view class="item_num">{{order.jinhuo}}</view>
						<view>合集进货金额</view>
					</view>
					<view class="deal_item d-c  d-c-c">
						<view class="item_num">{{order.lirun}}</view>
						<view>利润</view>
					</view>
				</view>
			</view>
		</view>

		<view class="shop_data">
			<view class="shop_data_title">订单结算</view>
			<view>
				<view v-for="(item,index) in orderList" :key="index" class="data_list">
					<view class="d-b-c mb20">
						<view class="datalist_item" style="width: 400rpx;">订单号：{{item.orderMaster.order_no}}</view>
						<view class="datalist_item orange" style="width:50rpx;" @click="todetail(item.settled_id)">详情
						</view>
					</view>
					<view class="d-b-c">
						<view class="datalist_item" style="width: 250rpx;">支付金额：{{item.pay_money}}</view>
						<view class="datalist_item" style="width: 250rpx;">结算金额：{{item.supplier_money}}</view>
					</view>
				</view>
				<!-- 没有记录 -->
				<view class="d-c-c p30" v-if="orderList.length==0 && !loadding">
					<text class="iconfont icon-wushuju"></text>
					<text class="cont">亲，暂无相关记录哦</text>
				</view>
				<uni-load-more v-else :loadingType="loadingType"></uni-load-more>
			</view>
		</view>

		<!-- 自定义垂直日期选择器弹窗 -->
		<u-popup v-model="showPicker" mode="bottom" border-radius="16px 16px 0 0" closeable
			:close-on-click-overlay="true" :safe-area-inset-bottom="true">
			<view class="picker-container">
				<view class="picker-header">
					<text class="picker-title">{{ pickerTitle }}</text>
				</view>

				<picker-view class="vertical-picker" :value="pickerValue" @change="onPickerChange"
					indicator-style="height: 44px;">
					<picker-view-column>
						<view class="picker-item" v-for="year in years" :key="year">{{ year }}年</view>
					</picker-view-column>
					<picker-view-column>
						<view class="picker-item" v-for="month in months" :key="month">{{ month }}月</view>
					</picker-view-column>
					<picker-view-column>
						<view class="picker-item" v-for="day in days" :key="day">{{ day }}日</view>
					</picker-view-column>
				</picker-view>

				<view class="picker-actions">
					<u-button plain hairline type="default" size="medium" custom-style="margin-right: 12px;"
						@click="showPicker = false">取消</u-button>
					<u-button type="primary" size="medium" @click="confirmDate">确定</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import uniLoadMore from "@/components/uni-load-more.vue";

	export default {
		data() {
			// 初始化日期数据
			const currentDate = new Date()
			const currentYear = currentDate.getFullYear()
			const currentMonth = currentDate.getMonth() + 1
			const currentDay = currentDate.getDate()

			// 生成年份范围（当前年前后5年）
			const years = Array.from({
				length: 11
			}, (_, i) => currentYear - 5 + i)

			return {
				// 日期选择器相关数据
				showPicker: false,
				pickerType: 'start', // 'start' 或 'end'
				pickerValue: [5, currentMonth - 1, currentDay - 1], // 默认选中当前日期
				years,
				months: Array.from({
					length: 12
				}, (_, i) => i + 1),
				days: [],
				startDate: null,
				endDate: null,
				minDate: new Date(currentYear - 1, 0, 1).getTime(),
				maxDate: new Date(currentYear + 1, 11, 31).getTime(),

				// 原有数据
				order: {},
				visit: {},
				orderList: [],
				loadding: true,
				no_more: false,
				page: 1,
				last_page: 0
			}
		},
		components: {
			uniLoadMore
		},
		computed: {
			startDateStr() {
				return this.formatDate(this.startDate)
			},
			endDateStr() {
				return this.formatDate(this.endDate)
			},
			pickerTitle() {
				return this.pickerType === 'start' ? '选择开始日期' : '选择结束日期'
			},
			/*加载中状态*/
			loadingType() {
				if (this.loadding) {
					return 1;
				} else {
					if (this.orderList.length != 0 && this.no_more) {
						return 2;
					} else {
						return 0;
					}
				}
			}
		},
		mounted() {
			this.info()
			this.getData();
		},
		methods: {
			// 日期选择器方法
			openPicker(type) {
				console.log(type, 'type')
				this.pickerType = type
				const date = type === 'start' ? this.startDate : this.endDate

				// 设置默认选中值
				if (date) {
					const d = new Date(date)
					const yearIndex = this.years.indexOf(d.getFullYear())
					const monthIndex = d.getMonth()
					const dayIndex = d.getDate() - 1

					this.pickerValue = [yearIndex, monthIndex, dayIndex]
				} else {
					// 默认选中当前日期
					const currentDate = new Date()
					const yearIndex = this.years.indexOf(currentDate.getFullYear())
					const monthIndex = currentDate.getMonth()
					const dayIndex = currentDate.getDate() - 1

					this.pickerValue = [yearIndex, monthIndex, dayIndex]
				}

				this.showPicker = true
				console.log(this.showPicker, 'type')
				this.updateDays()
			},

			onPickerChange(e) {
				this.pickerValue = e.detail.value
				this.updateDays()
			},

			updateDays() {
				const selectedYear = this.years[this.pickerValue[0]]
				const selectedMonth = this.months[this.pickerValue[1]]
				const daysInMonth = new Date(selectedYear, selectedMonth, 0).getDate()

				this.days = Array.from({
					length: daysInMonth
				}, (_, i) => i + 1)

				// 如果当前选中的日超过了新月份的天数，自动调整到最后一天
				if (this.pickerValue[2] >= daysInMonth) {
					this.pickerValue[2] = daysInMonth - 1
				}
			},

			confirmDate() {
				const selectedYear = this.years[this.pickerValue[0]]
				const selectedMonth = this.months[this.pickerValue[1]]
				const selectedDay = this.days[this.pickerValue[2]]

				const timestamp = new Date(selectedYear, selectedMonth - 1, selectedDay).getTime()

				if (this.pickerType === 'start') {
					this.startDate = timestamp
					// 如果结束时间早于新的开始时间，清空结束时间
					if (this.endDate && this.endDate < timestamp) {
						this.endDate = null
					}
				} else {
					// 检查结束时间不能早于开始时间
					if (this.startDate && timestamp < this.startDate) {
						uni.showToast({
							title: '结束时间不能早于开始时间',
							icon: 'none'
						})
						return
					}
					this.endDate = timestamp
				}

				this.showPicker = false
				// 当日期选择确认后，重新获取数据
				this.handleDateConfirm({
					startDate: this.startDate,
					endDate: this.endDate,
					startDateStr: this.startDateStr,
					endDateStr: this.endDateStr
				})
			},

			formatDate(timestamp) {
				if (!timestamp) return ''
				const date = new Date(timestamp)
				const year = date.getFullYear()
				const month = (date.getMonth() + 1).toString().padStart(2, '0')
				const day = date.getDate().toString().padStart(2, '0')
				return `${year}-${month}-${day}`
			},

			handleDateConfirm(range) {
				console.log('选择的时间范围:', range)
				// 在这里处理选择的时间范围，可以调用API获取对应时间段的数据
				this.page = 1
				this.orderList = []
				this.no_more = false
				this.getData()
			},

			// 原有方法
			info() {
				let self = this;
				self._post('supplier.index/dataCenter', {
					startTime: this.startDateStr ? this.formatDate(this.startDate, 'yyyy-MM-dd') + ' 00:00:00' :
						'00:00:00',
					endTime: this.endDateStr ? this.formatDate(this.endDate, 'yyyy-MM-dd') + ' 23:59:59' :
						'23:59:59'
				}, (res) => {
					if (res.code == 1) {
						self.order = res.data.data.rent;
					}
				})
			},

			onReachBottom() {
				let self = this;
				if (self.no_more) {
					return;
				}
				self.page++;
				if (self.page <= self.last_page) {
					self.getData();
				} else {
					self.no_more = true;
				}
			},

			getData(e) {
				let self = this;
				let page = self.page;
				self.loadding = true;
				uni.showLoading({
					title: '加载中'
				})
				self._post('supplier.index/storedata', {
					page: page || 1,
					start_time: this.startDateStr || '',
					end_time: this.endDateStr || ''
				}, (res) => {
					self.orderList = self.orderList.concat(res.data.ordersettle.data);
					self.visit = res.data.visit;
					self.last_page = res.data.ordersettle.last_page;
					if (res.data.ordersettle.last_page <= 1) {
						self.no_more = true;
					} else {
						self.no_more = false;
					}
					self.loadding = false;
					uni.hideLoading()
				})
			},

			todetail(id) {
				this.gotoPage('/pages/user/my_shop/my_shop_detail?settled_id=' + id);
			}
		}
	}
</script>

<style scoped>
	.shop_data {
		width: 90%;
		padding: 30rpx;
		background-color: white;
		margin: 0 auto;
		margin-top: 30rpx;
		box-sizing: border-box;
		border-radius: 30rpx;
		color: #585858;
	}

	.shop_data_title {
		font-size: 30rpx;
		margin-bottom: 50rpx;
		font-weight: 800;
	}

	.deal .title,
	.visit .title {
		font-size: 30rpx;
		padding-bottom: 15rpx;
	}

	.deal_list {
		flex-wrap: wrap;
	}

	.deal_item {
		width: 33%;
		margin: 20rpx 0;
	}

	.item_num {
		margin-bottom: 20rpx;
		color: #6EC2CB;
	}

	.datalist_item {
		/* text-align: center; */
	}

	.data_list {
		border-top: 1rpx solid #CCCCCC;
		padding: 20rpx 20rpx;
	}

	/* 时间范围选择器样式 */
	.time-range-picker {
		background-color: #fff;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		padding: 20rpx;
	}

	.time-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15rpx 0;
	}

	.time-item:not(:last-child) {
		border-bottom: 1rpx solid #f5f5f5;
	}

	.time-value {
		display: flex;
		align-items: center;
	}

	.time-value text {
		color: #999;
		margin-right: 10rpx;
	}

	/* 日期选择器弹窗样式 */
	.picker-container {
		padding: 0 30rpx 30rpx;
	}

	.picker-header {
		padding: 30rpx 0;
		text-align: center;
	}

	.picker-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.vertical-picker {
		width: 100%;
		height: 400rpx;
	}

	.picker-item {
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		font-size: 28rpx;
	}

	.picker-actions {
		display: flex;
		justify-content: center;
		margin-top: 30rpx;
	}
</style>